<?php

namespace app\admin\controller\tongcheng;

use addons\tongcheng\enum\ClientType;
use addons\tongcheng\library\WechatService;
use app\admin\model\tongcheng\SubscribeMessageModel;
use app\common\controller\Backend;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;

/**
 * 订阅消息
 *
 * @icon fa fa-circle-o
 */
class SubscribeMessage extends Backend
{
    protected $noNeedRight = ['init'];

    /**
     * SubscribeMessageModel模型对象
     * @var \app\admin\model\tongcheng\SubscribeMessageModel
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\tongcheng\SubscribeMessageModel;
        $this->view->assign("clientList", $this->model->getClientList());
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 初始化订阅消息模板
     */
    public function init()
    {
        $init_data = [
            [
                'tid'   => 33722,
                'kids'  => [1, 8, 6, 5],
                'desc'  => '订单接单通知',
                'scene' => 'delivery_order',
            ],
            [
                'tid'   => 44659,
                'kids'  => [1, 2, 3, 5, 6],
                'desc'  => '司机行程通知',
                'scene' => 'delivery_order',
            ],
            [
                'tid'   => 36518,
                'kids'  => [2, 3, 4],
                'desc'  => '退款成功通知',
                'scene' => 'delivery_refund',
            ],
            [
                'tid'   => 40787,
                'kids'  => [1, 2, 3, 4, 5],
                'desc'  => '行程送达通知',
                'scene' => 'delivery_order',
            ],
            // [
            //     'tid'   => 33676,
            //     'kids'  => [1, 3, 4],
            //     'desc'  => '订单完成通知',
            //     'scene' => 'delivery_order',
            // ],
        ];

        $app = WechatService::getMiniApp();

        $fail_count = 0;
        $inserts    = [];
        foreach ($init_data as $data) {
            $words       = $app->subscribe_message->getTemplateKeywords($data['tid']);
            $fields      = [];
            $fields_json = [];
            foreach ($words['data'] as $word) {
                if (in_array($word['kid'], $data['kids'])) {
                    $fields[]      = $word['name'];
                    $fields_json[] = [
                        'name'  => $word['name'],
                        'kid'   => $word['kid'],
                        'rule'  => $word['rule'],
                        'param' => $word['rule'] . $word['kid'],
                    ];
                }
            }

            // 添加模板
            $result = $app->subscribe_message->addTemplate($data['tid'], $data['kids'], $data['desc']);
            if ($result && $result['errmsg'] == 'ok') {
                $inserts[] = [
                    'client'      => ClientType::CUSTOMER,
                    'tid'         => $data['tid'],
                    'name'        => $data['desc'],
                    'scene'       => $data['scene'],
                    'fields'      => implode(',', $fields),
                    'fields_json' => json_encode($fields_json),
                    'template_id' => $result['priTmplId'],
                ];

                // 删除已有的模板
                $old = SubscribeMessageModel::where('name', $data['desc'])->find();
                if ($old) {
                    if ($old['template_id']) {
                        $result = $app->subscribe_message->deleteTemplate($old['template_id']);
                    }

                    $old->delete();
                }
            }

        }
        $this->model->saveAll($inserts);

        $success_count = count($inserts);
        $this->success("初始化成功{$success_count}条，失败{$fail_count}条");
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk       = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                if ($item['template_id']) {
                    $app = WechatService::getMiniApp();
                    $app->subscribe_message->deleteTemplate($item['template_id']);
                }
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

}
